﻿#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;

#if UNITY_IPHONE
    #if UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
    using UnityEditor.iOS.Xcode.Custom;
    using UnityEditor.iOS.Xcode.Custom.Extensions;
    #else
    using UnityEditor.iOS.Xcode;
    using UnityEditor.iOS.Xcode.Extensions;
    #endif
	// #if UNITY_XCODE_API_BUILD
	// using UnityEditor.iOS.Xcode;
 //    using UnityEditor.iOS.Xcode.Extensions;
	// #else
	// using UnityEditor.iOS.Xcode.Custom;
 //    using UnityEditor.iOS.Xcode.Custom.Extensions;
	// #endif
#endif

using System.IO;



#if UNITY_IPHONE
public class XcodeSetting : MonoBehaviour
{
    [PostProcessBuild(999)]
    public static void OnPostprocessBuild(BuildTarget buildTarget, string path)
    {
        string version = Application.unityVersion;
        Debug.Log("Version of the runtime: " + Application.unityVersion);
        //if (BuildTarget == BuildTarget.iOS)
        BuildTarget currentTarget;
        #if UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
            currentTarget = BuildTarget.iPhone;
        #else
            currentTarget = BuildTarget.iOS;
        #endif
        if (buildTarget == currentTarget)
        {
            Debug.Log("OnPostprocessBuild Xcode ProjectPath:" + path);
            string projPath = PBXProject.GetPBXProjectPath(path);//獲取.xcodeproj文件的路徑

            PBXProject proj = new PBXProject();//new()一個PBXProject對象，然后從上面獲取的路徑中讀出字符串。
            string contents = File.ReadAllText(projPath);
            proj.ReadFromString(contents);

            string target = proj.TargetGuidByName(PBXProject.GetUnityTargetName());//獲取targetGUID

            // add extra framework(s)
            proj.AddFrameworkToProject(target, "WebKit.framework", false);

			//去掉BITCODE 发布bug
		    proj.SetBuildProperty(target, "ENABLE_BITCODE", "NO");

            // 添加鏈接器
            proj.AddBuildProperty(target, "OTHER_LDFLAGS", "-ObjC -all_load");//Other Linker Flags  在ios開發過程中，有時候會用到第三方的靜態庫(.a文件)，然后導入后發現編譯正常但運行時會出現selector not recognized的錯誤，從而導致app閃退。
            
            proj.AddBuildProperty(target, "LIBRARY_SEARCH_PATHS", "$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)");

            //添加framework搜索路径
            proj.AddBuildProperty(target, "FRAMEWORK_SEARCH_PATHS", "$(PROJECT_DIR)/Frameworks/Plugins/ios");

            //proj.AddLocalization("Localizable.strings", "Localizable.strings", "Localizable.strings");

            //添加Pod配置
            var fileName = "Podfile";
            //源路径
            var sourcePath = Path.Combine("Assets/Plugins/ios",fileName);
            //目标路径
            var targetPath = Path.Combine(path,fileName);
            //复制文件
            File.Copy(sourcePath,targetPath);
            //添加到xcode依赖资源
            proj.AddFileToBuild(target,proj.AddFile(fileName,fileName,PBXSourceTree.Source));

            //复制多语言
            // CopyDirectory (proj,target,path,"Assets/Plugins/ios/multi_language", path);

            // proj.AddFileToBuild(target,proj.AddFile("zh-Hans.lproj/Localizable.strings","zh-Hans.lproj/Localizable.strings",PBXSourceTree.Source));
            // proj.AddFileToBuild(target,proj.AddFile("zh-Hant.lproj/Localizable.strings","zh-Hant.lproj/Localizable.strings",PBXSourceTree.Source));
            // proj.AddFileToBuild(target,proj.AddFile("en.lproj/Localizable.strings","en.lproj/Localizable.strings",PBXSourceTree.Source));


            // 创建文件夹
            var frameworkPath = path+"/Frameworks";
            Directory.CreateDirectory (frameworkPath);
            frameworkPath = frameworkPath + "/Plugins";
            Directory.CreateDirectory (frameworkPath);
            frameworkPath = frameworkPath + "/ios";
            Directory.CreateDirectory (frameworkPath);


            // //添加frameworks
            // var sourceGamesdkFramewok = "Assets/Plugins/ios/Frameworks/gamesdkFramework.framework";
            // var targetGamesdkFramewok = frameworkPath+"/gamesdkFramework.framework";
            // //复制文件
            // File.Copy(sourceGamesdkFramewok,targetGamesdkFramewok);
            // //添加到xcode依赖资源
            // proj.AddFileToBuild(target,proj.AddFile(targetGamesdkFramewok,targetGamesdkFramewok,PBXSourceTree.Source));


            // //复制bundle
            // var sourceGamesdkBundle = "Assets/Plugins/ios/Frameworks/gamesdkResource.bundle";
            // var targetGamesdkBundle = frameworkPath+"/gamesdkResource.bundle";
            // //复制文件
            // File.Copy(sourceGamesdkBundle,targetGamesdkBundle);
            // //添加到xcode依赖资源
            // proj.AddFileToBuild(target,proj.AddFile(targetGamesdkBundle,targetGamesdkBundle,PBXSourceTree.Source));

            CopyDirectory(proj,target,path,"Assets/Plugins/ios/Frameworks", frameworkPath);

           
            proj.AddFileToBuild(target,proj.AddFile("Frameworks/Plugins/ios/gamesdkFramework.framework","Frameworks/Plugins/ios/gamesdkFramework.framework",PBXSourceTree.Source));
            // string fileGuid = proj.AddFile("Frameworks/Plugins/ios/gamesdkFramework.framework", "Frameworks/Plugins/ios/gamesdkFramework.framework", PBXSourceTree.Sdk);
            // PBXProjectExtensions.AddFileToEmbedFrameworks(proj, target, fileGuid);

            proj.AddFileToBuild(target,proj.AddFile("Frameworks/Plugins/ios/gamesdkResource.bundle","Frameworks/Plugins/ios/gamesdkResource.bundle",PBXSourceTree.Source));
			


            // 保存设置
			File.WriteAllText(projPath, proj.WriteToString());

    		// Get plist
      		string plistPath = path + "/Info.plist";
      		PlistDocument plist = new PlistDocument();
      		plist.ReadFromString(File.ReadAllText(plistPath));

      		// Get root
      		PlistElementDict rootDict = plist.root;

      		PlistElementArray urlTypes = rootDict.CreateArray("LSApplicationQueriesSchemes");
      		urlTypes.AddString("mqqapi");
      		urlTypes.AddString("mqq");
            rootDict.SetString("AppID", "7fa2d744123f6a65b14569fb24e913a1");

            // 添加https 权限
            PlistElementDict https = rootDict.CreateDict("NSAppTransportSecurity");
            https.SetBoolean("NSAllowsArbitraryLoads",true);

            // 多语言支持列表
            PlistElementArray localizations = rootDict.CreateArray("CFBundleLocalizations");
            localizations.AddString("zh_CN");
            localizations.AddString("zh_TW");
            localizations.AddString("en");

      		// Write to file
      		File.WriteAllText(plistPath, plist.WriteToString());
       }
    }

    static void CopyDirectory(PBXProject proj,string target,string path,string sourceDirectory, string targetDirectory) 
    {
        if (!Directory.Exists(sourceDirectory) || !Directory.Exists(targetDirectory)) 
        {
            return;
        }
        DirectoryInfo sourceInfo = new DirectoryInfo(sourceDirectory);
        FileInfo[] fileInfo = sourceInfo.GetFiles();
        foreach (FileInfo fiTemp in fileInfo) 
        {
            var fileName = fiTemp.Name;
            if(!fileName.EndsWith(".meta") && !fileName.EndsWith(".DS_Store")){
                
            //源路径
            //var sourceFilePath = Path.Combine(sourceDirectory,fileName);
            var sourceFilePath = sourceDirectory+"/"+fileName;
            //目标路径
            var targetFilePath = Path.Combine(targetDirectory,fileName);
            //复制文件
            File.Copy(sourceFilePath,targetFilePath,true);
            //添加到xcode依赖资源
            Debug.Log("sourceInfo.Name:"+sourceInfo.Name+"/"+fileName);
            var targetPath = targetFilePath.Replace(path+"/","");
            Debug.Log("targetPath:"+targetPath);
            //proj.AddFileToBuild(target,proj.AddFile(targetPath,targetPath,PBXSourceTree.Source));

            }
        }
        DirectoryInfo[] diInfo = sourceInfo.GetDirectories();
        foreach (DirectoryInfo diTemp in diInfo) 
        {
            string sourcePath = diTemp.FullName;
            Debug.Log("子文件夹："+sourcePath);
            string targetPath = targetDirectory + "/" + diTemp.Name;
            Debug.Log("子文件夹targetPath："+targetPath);
            Directory.CreateDirectory(targetPath);
            CopyDirectory(proj,target,path,sourcePath,targetPath);
            // string projPath = PBXProject.GetPBXProjectPath(path);
            // File.WriteAllText(projPath, proj.WriteToString());
            // var fileGuid = proj.AddFolderReference(sourcePath, diTemp.Name, PBXSourceTree.Source);
            // proj.AddFileToBuild(target, fileGuid);
        }
    }
}

#endif
#endif